package com.xzbd.demonstration;

import org.apache.commons.lang.math.RandomUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

import com.xzbd.constants.ColorConstant;
import com.xzbd.utils.CompositeUtil;
import com.xzbd.utils.SWTResourceManager;

public class ScrollGoodListTest {
	public static void main(String[] args) {
		Display display = new Display();
		Image image1 = display.getSystemImage(SWT.ICON_WORKING);
		Image image2 = display.getSystemImage(SWT.ICON_QUESTION);
		Image image3 = display.getSystemImage(SWT.ICON_ERROR);

		Shell shell = new Shell(display);
		shell.setText("SWT-内容滚动-商品列表");
		shell.setLayout(new FillLayout());

		// 生成滚动容器
		Composite scContent = CompositeUtil.getAutoFillScrollCmp(shell);

		for (int i = 0; i <= 50 + RandomUtils.nextInt(50); i++) {
			Composite itemCmp = new Composite(scContent, SWT.NONE);
			itemCmp.setLayoutData(new RowData(100, 120));
			Boolean[] lineTags = { false };
			int j = i;
			itemCmp.addPaintListener(e -> {
				GC gc = e.gc;
				Image img = image1;
				if (j % 3 == 1)
					img = image2;
				if (j % 3 == 2)
					img = image3;

				Rectangle clientArea = itemCmp.getClientArea();
				Rectangle imgBounds = img.getBounds();
				int imgWidth = (clientArea.width - imgBounds.width) / 2;
//				int imgHeight = (clientArea.height - imgBounds.height) / 2;
				gc.drawImage(img, imgWidth, 15);
				
				String text = "图 " + (j + 1) ;
				Font font = SWTResourceManager.getFont("Microsoft YaHei", 14, SWT.NORMAL);
				if (lineTags[0]) {
					gc.setLineWidth(5);
					gc.setForeground(ColorConstant.MAIN_BLUE);
					gc.drawRectangle(0, 0, clientArea.width, clientArea.height);
					font = SWTResourceManager.getBoldFont(font);
				}
				
				gc.setFont(font);
				Point textExtentPoint = gc.textExtent(text);
				gc.setForeground(ColorConstant.MAIN_BLUE);
				int textWidth =  (clientArea.width - textExtentPoint.x) / 2;
				int textHeight = clientArea.height - textExtentPoint.y - 10;
				gc.drawText(text, textWidth, textHeight, true);
			});

			// 事件绑定
			Listener enterListener = e -> {
				lineTags[0] = true;
				itemCmp.redraw();
			};

			itemCmp.addListener(SWT.MouseEnter, enterListener);

			Listener exitListener = e -> {
				lineTags[0] = false;
				itemCmp.redraw();
			};
			itemCmp.addListener(SWT.MouseExit, exitListener);

		}


		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		display.dispose();
	}
	
	
}
